<?php

namespace App\Http\Controllers;

use Hash;
use DB;
use Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Common\File;
use App\Common\uploadFileConfig;
use App\Common\excuteState;
use App\Models\UserM;
use Illuminate\Database\QueryException;
use App\Models\UserFansM;
use App\Models\UserFollowM;

class UserController extends Controller {

    public function __construct(Request $request) {
        $this->request = $request;
    }

    public $folder = ['1', '2', '3', '4', '5', '6', '7', '8'];

    public function test() {
        $users = DB::select('select * from item where id = ?', [1]);
        return view('welcome2')->with('name', $users);
    }

    public function index() {
//        $users = DB::select('select * from item where id = ?', [1]);
//        return view('welcome2')->with('name', $users);
        echo "index user";
    }

    public function addUser() {
//        $date = new \DateTime();
//        $time = strtotime($date);
//        $time = $date->getTimestamp();
        $time = date("Y-m-d H:i:s");
        $password = Hash::make('123');
        DB::table('users')->insert(['name' => "guo", 'email' => 'guowc456@126.com', 'password' => $password, 'created_at' => $time, 'updated_at' => $time]);
        echo 'ok';
        die();
    }

    public function check() {
        $password = '123';
        if (Auth::attempt(['email' => 'guowc456@126.com', 'password' => $password])) {
            die("ok");
        }
        die("no");
    }

    public function isWho() {
        $ID = 7;
        // 从数据库表中取得单一数据列的单一字段
        $user = DB::table('users')->where('id', $ID)->pluck('id');
        $user = DB::table('users')->lists('id');
        return $user;
    }

    public function addItem() {
        // 从数据库表中取得单一数据列的单一字段
        $user = DB::table('users')->where('id', $ID)->pluck('id');
        $user = DB::table('users')->lists('id');
        return $user;
    }

    public function saveImage() {
        $ID = 7;
        // 从数据库表中取得单一数据列的单一字段
        $user = DB::table('users')->where('id', $ID)->pluck('id');
        $user = DB::table('users')->lists('id');
        return $user;
    }

    public function updatePassword() {
        $user = Auth::user();
        return view("auth/updatePassword", ['username' => $user->name]);
    }

    public function update() {
        $user = Auth::user();
        $username = Input::get('username');
        $oldPass = Input::get('password');
        $newPass = Input::get('password_new');
        $newPass2 = Input::get('password_new2');
        $userDataObj = User::where('name', $username)->first();
        if ($userDataObj !== null && $username !== $user->name) {
            $user = User::find($userDataObj->id);
        } else if (!Auth::attempt(['name' => $user->name, 'password' => $oldPass])) {
            die('密码不对');
        }
        if ($newPass === $newPass2) {
            $user->password = Hash::make($newPass);
            $user->save();
        } else {
            return view('auth/updatePassword', ['username' => $user->name]);
        }
        return redirect('home');
    }

    public function userInfo($userId) {
        $user = DB::table('users')->select('id', "mobilephone", "name", "email", "created_at")->where('id', $userId)->first();
        return $user;
    }

    public function ready() {
        $token = csrf_token();
        return json_encode(["_token" => $token]);
    }

    public function login(Request $request) {
        $userName = $request->input("userName");
        $passWord = $request->input('passWord');
        $info = null;
//        if (Auth::check()) {
//            Auth::logout();
//            die("hhs");
//        }
        if (Auth::attempt(['name' => $userName, 'password' => $passWord])) {
            $user = Auth::user();
            $info = $this->userInfo($user->id);
            return ['isLogin' => true, 'userinfo' => $info];
        }
        return ['isLogin' => false, 'userinfo' => $info];
    }

        public function postQa() {
        $jsonStr = $this->request->input('datas');
        $datas = json_decode($jsonStr, true);
//        var_dump($datas);die();
        $toDatabaseDatas = [];
        foreach ($datas as $key => $value) {
            $toDatabaseDatas[$key] = implode(';', $value);
        }
        $qa_table = 'lee_qa';
        $rowData = DB::table($qa_table)->where('deviceid', $datas['deviceid'][0])->first();
        if ($rowData) {
            DB::table($qa_table)->where("deviceid", $datas['deviceid'][0])->update($toDatabaseDatas);
        } else {
            DB::table($qa_table)->insert($toDatabaseDatas);
        }
        return 'success';
    }
    
    
    // added by lee 
    
    /**
     * 获得用户可更新的非头像信息集合
     * @param unknown $userid
     */
    public  static  function userInfo4Update($userid){
        try {
            return excuteState::OKwithDatas(UserM::userInfo($userid));
        } catch (QueryException $e) {
            return excuteState::selectError();
        }
    }
    
    
    public  static  function tup(){
        UserM::updateInfo([]);
    }
    
    /**
     * 更新用户信息
     * 出入数据格式
     * {"userInfo":
				{"id":"id1","avatar":"imgPath1","nname":"nickname","gender":"nan",
				    "address":'address',"height":181,"weight":80,"career":"carear1","birthd":"20161225"
				}
			}
     * @param Request $request
     */
    public static function updateInfo(Request $request){
        try {
             //$data=["id"=>5,"avatar"=>"uploadfile","height"=>234];
            $data=json_decode($request->input('userInfo'),true);
            
            $avatarObj=$request->file($data['avatar']);
            
            $upFileCon=new uploadFileConfig();
            // 存储根目录
            $imgRoot=$upFileCon->imgRootPath();
            $avatarF=$upFileCon->avatarFolder();
            $thumbAvatarF=$upFileCon->thumbAvatarFolder();
            
            // user id
            $userID=$data['id'];
            
            $avatarName=File::base10to62(File::getMicSec());
//             $avatarName=File::base10to62($userID);
            
            // 获得用户 的 name和 avatar
             $existFileName=UserM::getNameAvatar($userID);
             if($existFileName !=null && $existFileName['avatar']!=null){
                 //删除原始数据
                $fileFullPath=$imgRoot.DIRECTORY_SEPARATOR.$existFileName['avatar'];
//                 // thumbavatar路径
                $thumbAvatarPath=str_replace($avatarF, $thumbAvatarF, $fileFullPath);
                File::delete($fileFullPath);
                File::delete($thumbAvatarPath);
             }
            $imgWidth=0;
            $imgHeiht=0;
            // 上传 头像
            $saveFileName=File::uploadImgFile($avatarObj, $imgRoot, $avatarF,
                $thumbAvatarF, $avatarName, 0.3,$imgWidth,$imgHeiht);
            
            $urlRoot=env('IMG_RUL');
            // 头像存储链接
            $data['avatar']=$urlRoot.'/'.$saveFileName;
            
            // 存储到数据库
            try {
                UserM::updateInfo($data);
                return excuteState::OKwithDatas(['newAvatar'=>$saveFileName]);
            } catch (QueryException $e) {
                return excuteState::updateError();
            }
            
        } catch (\Exception $e) {
            return excuteState::otherError();
        }

    }
    
    /**
     * 更新用户非头像信息
     * @param Request $request
     *出入数据格式
     * {"userInfo":
				{"id":"id1","nname":"nickname","gender":"nan",
				    "address":'address',"height":181,"weight":80,"career":"carear1","birthd":"20161225"
				}
			}
     */
    static public function updateProperty(Request $request){
        $data=json_decode($request->input('userInfo'),true);
        // 存储到数据库
        try {
            UserM::updateInfo($data);
            return excuteState::OK();
        } catch (QueryException $e) {
            return excuteState::updateError();
        }
    }
    
    /**
     * 添加粉丝
     * @param Request $request
     * 传入数据类型 {'userInfo':{'userid':1,'fansid':2}}
     */
    static public function addFans(Request $request){
       $datas=json_decode($request->input('userInfo'),true);
        //$datas=['userid'=>3,'fansid'=>5];
        DB::beginTransaction();
        try {
            UserFansM::newFansItem($datas);
            //粉丝数++
            UserM::userFansPlus($datas['userid']);
            DB::commit();
            return excuteState::Ok();
            
        } catch (QueryException $e) {
            DB::rollBack();
            return excuteState::insertError();
        }  
    }
    
    
    /**
     * 依据 userid返回其 粉丝列表
     * @param bigint $userid 用户id
     * 返回形式 
     * [{"userid":5,"username":"user5",
     *  "nickname":"nickname5","avatar":"avatar\/16121015\/D.JPG"}]
     */
    static public function getFans($userid){
        try{
            $rtData= UserFansM::getFans($userid);
            return excuteState::OKwithDatas($rtData);
            
        }Catch(QueryException $e){
            return excuteState::selectError();
        }
        
    }
    
    /**
     * 依据 userid返回其 关注列表
     * @param bigint $userid 用户id
     * 返回形式
     * [{"userid":5,"username":"user5",
     *  "nickname":"nickname5","avatar":"avatar\/16121015\/D.JPG"}]
     */
    static public function getFollows($userid){
        try{
            $rtData= UserFollowM::getFollows($userid);
            return excuteState::OKwithDatas($rtData);
    
        }Catch(QueryException $e){
            return excuteState::selectError();
        }
    
    }
    
    
    /**
     * 移除粉丝
     * @param Request $request
     * 传入数据类型 {'userInfo':{'userid':1,'fansid':2}}
     */
    static public function removeFans(Request $request){
        $datas=json_decode($request->input('userInfo'),true);
        //$datas=['userid'=>3,'fansid'=>5];
        DB::beginTransaction();
        try {
            UserFansM::deltFansItem($datas);
            //粉丝数--
            UserM::userFansMin($datas['userid']);
            DB::commit();
            return excuteState::Ok();
    
        } catch (QueryException $e) {
            DB::rollBack();
            return excuteState::insertError();
        }
    }
    
    
    
    
    
    /**
     * 添加 关注
     * @param Request $request
     * 传入数据类型 {'userInfo':{'userid':1,'followid':2}}
     */
    static public function addFollow(Request $request){
        $datas=json_decode($request->input('userInfo'),true);
        //$datas=['userid'=>3,'followid'=>5];
        $fansDatas=[];
        $fansDatas['userid']=$datas['followid'];
        $fansDatas['fansid']=$datas['userid'];
        
        DB::beginTransaction();
        try {
            // 添加关注
            UserFollowM::newFollowItem($datas);
            // 关注数++
            UserM::userFollowPlus($datas['userid']);
            
            // 添加粉丝
            UserFansM::newFansItem($fansDatas);
            //粉丝数++
            UserM::userFansPlus($fansDatas['userid']);
            DB::commit();
            return excuteState::Ok();
    
        } catch (QueryException $e) {
            DB::rollBack();
            return excuteState::insertError();
        }
    }
    
    /**
     * 移除粉丝
     * @param Request $request
     * 传入数据类型 {'userInfo':{'userid':1,'followid':2}}
     */
    static public function removeFollow(Request $request){
        $datas=json_decode($request->input('userInfo'),true);
        //$datas=['userid'=>3,'followid'=>5];
        
        $fansDatas=[];
        $fansDatas['userid']=$datas['followid'];
        $fansDatas['fansid']=$datas['userid'];
        
        DB::beginTransaction();
        try {
            
            // 删除关注
            UserFollowM::deltFollowItem($datas);
            //关注数--
            UserM::userFollowMin($datas['userid']);
            
            // 删除粉丝
            UserFansM::deltFansItem($fansDatas);
            //粉丝数--
            UserM::userFansMin($fansDatas['userid']);
            
            DB::commit();
            return excuteState::Ok();
    
        } catch (QueryException $e) {
            DB::rollBack();
            return excuteState::insertError();
        }
    }
    
    
    /**
     * 根据userid 返回其统计信息
     * @param bigint $userid 用户id
     * 返回数据形式
     *
     */
    static public function userStatic($userid){
        try{
            $rtData= UserM::userStatic($userid);
            return excuteState::OKwithDatas($rtData);
    
        }Catch(QueryException $e){
            return excuteState::selectError();
        }
    }
    
    /***
     * 返回 用户详细信息和统计信息
     * @param unknown $userid
     * @return Ambigous <multitype:number , multitype:number string >
     */
    static public function userDetialStatic($userid){
        try{
            $rtData= UserM::DetialStatic($userid);
            return excuteState::OKwithDatas($rtData);
        
        }Catch(QueryException $e){
            return excuteState::selectError();
        }
    }

}
